package com.falcon.modules.controller;

import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.falcon.modules.domain.bo.MenuBo;
import com.falcon.modules.domain.dto.Menu;
import com.falcon.modules.domain.dto.Role;
import com.falcon.modules.domain.dto.User;
import com.falcon.modules.service.IMenuService;
import com.falcon.modules.service.IRoleService;
import com.falcon.modules.service.IUserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springside.modules.utils.collection.CollectionUtil;
import org.springside.modules.utils.mapper.JsonMapper;

import java.util.*;

/**
 * mybatis-plugs参考：https:*gitee.com/baomidou/mybatisplus-spring-boot
 */
@RestController
@RequestMapping("menu")
@Slf4j
public class MenuController {

    @Autowired
    private IMenuService menuService;

    @Autowired
    private IRoleService roleService;

    @Autowired
    private IUserService userService;

    /**
     * 获取当前登陆用户所有有权限的菜单
     * <p>
     * [{
     * "id": "顶部菜单",
     * "text": "首页",
     * "menu": [{
     * "text": "一级菜单",
     * items: [{
     * id: 'main-menu',
     * text: '二级菜单',
     * href: 'main/menu.php'
     * },
     * {
     * id: 'second-menu',
     * text: '二级菜单',
     * href: 'main/second-menu.php'
     * }]
     * }]
     * }]
     *
     * @return
     */
    @RequestMapping("userMenuList")
    public Object userMenuList() {
        User curUser = (User) SecurityUtils.getSubject().getPrincipal();
        Long uid = curUser.getId();

        try {
            User user = userService.selectById(uid);

            log.info(JsonMapper.defaultMapper().toJson(user));

            if (user == null || StringUtils.isBlank(user.getRoleIds())) {
                log.error("用户 id : [{}] 用户没有分配角色", uid);
            }

            List<Role> userRoleList = roleService.selectBatchIds(Arrays.asList(user.getRoleIds().split(",")));
            if (CollectionUtil.isEmpty(userRoleList)) {
                log.error("用户 id : [{}] 用户的角色没有找到", uid);
            }


            //Map<id,Menu>
            Map<Long, Menu> menuMap = new HashMap<Long, Menu>();
            for (Role role : userRoleList) {
                List<Menu> userMenuList = menuService.selectBatchIds(Arrays.asList(role.getMenuIds().split(",")));
                if (CollectionUtil.isNotEmpty(userMenuList)) {
                    for (Menu menu : userMenuList) {
                        menuMap.put(menu.getId(), menu);
                    }
                }
            }


            JSONArray result = new JSONArray();
            List<MenuBo> one = new ArrayList<MenuBo>();
            Map<Long, List<MenuBo>> m2 = new HashMap<Long, List<MenuBo>>();
            Map<Long, List<MenuBo>> m3 = new HashMap<Long, List<MenuBo>>();


            for (Long menuId : menuMap.keySet()) {
                Menu m = menuMap.get(menuId);
                if (m != null && m.getType() == 1) {
                    //顶部导航
                    MenuBo menuBo = new MenuBo(m);
                    one.add(menuBo);
                    List<MenuBo> two = new ArrayList<MenuBo>();
                    m2.put(m.getId(), two);

                    //一级菜单
                    for (Long mId : menuMap.keySet()) {
                        Menu mm = menuMap.get(mId);
                        if (mm.getPid() == m.getId()) {
                            two.add(new MenuBo(mm));

                            List<MenuBo> three = new ArrayList<MenuBo>();
                            m3.put(mm.getId(), three);

                            //二级菜单
                            for (Long mmId : menuMap.keySet()) {
                                Menu mmm = menuMap.get(mmId);
                                if (mmm.getPid() == mm.getId()) {
                                    if (mmm.getHomePage() != null && mmm.getHomePage()) {
                                        menuBo.setHomePage(mmm.getUrl());
                                    }
                                    three.add(new MenuBo(mmm));
                                }
                            }
                        }
                    }
                }
            }


            Collections.sort(one);
            for (MenuBo mb1 : one) {
                result.add(mb1);
                List<MenuBo> menus = m2.get(Long.parseLong(mb1.getId()));
                if (menus == null) {
                    continue;
                }
                Collections.sort(menus);
                mb1.setMenu(menus);
                for (MenuBo mb2 : menus) {
                    List<MenuBo> items = m3.get(Long.parseLong(mb2.getId()));
                    if (items == null) {
                        continue;
                    }
                    Collections.sort(items);
                    for (MenuBo mb3 : items) {
                    }
                    mb2.setItems(items);
                }
            }

            return result;
        } catch (Exception e) {
            log.error("用户 id : [{}] 获取菜单列表异常", uid, e);
        }

        return null;
    }


    @RequestMapping("")
    public Object roleMenuList(Long roleId) {
        try {
            Role role = roleService.selectById(roleId);
            Menu menu = new Menu();
            menu.setState(1);
            List<Menu> menuList = menuService.selectList(new EntityWrapper<Menu>(menu));


        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    @RequestMapping("list")
    public Page<Menu> list(int page, int pageSize) {
        return menuService.selectPage(new Page<Menu>(page, pageSize), null);
    }

    @RequestMapping("selectBatchIds")
    public List selectBatchIds(Integer[] ids) {
        System.out.println(JsonMapper.INSTANCE.toJson(ids));
        return menuService.selectBatchIds(Arrays.asList(ids));
    }

    @RequestMapping("get")
    public Menu get(Menu menu) {
        return menuService.selectOne(new EntityWrapper<Menu>(menu));
    }
}
